package com.bjqh.edu.UI.Activity.TeacherPersonal;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bjqh.edu.Base.AppConstants;
import com.bjqh.edu.Bean.Grade;
import com.bjqh.edu.Bean.Login;
import com.bjqh.edu.Bean.Stulist;
import com.bjqh.edu.R;
import com.bjqh.edu.UI.Activity.Login.LoginActivity;
import com.bjqh.edu.UI.Utils.CropUtils;
import com.bjqh.edu.UI.Utils.FileUtil;
import com.bjqh.edu.UI.Utils.MyApplication;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

public class TeacherPlannActivity extends AppCompatActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_qx)
    TextView tvQx;
    @BindView(R.id.rl_top_tilte)
    RelativeLayout rlTopTilte;
    @BindView(R.id.et_title)
    EditText etTitle;
    @BindView(R.id.iv_xz)
    LinearLayout ivXz;
    @BindView(R.id.iv_wd)
    ImageView ivWd;
    @BindView(R.id.tv_ok)
    Button tvOk;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.tv_wdname)
    TextView tvWdname;
    @BindView(R.id.et_subject)
    TextView etSubject;
    @BindView(R.id.iv_stu)
    LinearLayout ivStu;
    private File file;
    private Uri uri;
    String[] stu;
    int uid;
    String stuname;
    Dialog alertDialog;
    //声明选中项变量
    // public int selectedCityIndex = 0;
    public List<Stulist.DataBean> dataBeen;
    private static final int REQUEST_CODE_TAKE_PHOTO = 1;
    private static final int REQUEST_CODE_ALBUM = 2;
    private static final int REQUEST_CODE_CROUP_PHOTO = 3;
    private ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_teacher_plann);
        ButterKnife.bind(this);
        dialog = new ProgressDialog(this);
        dialog.setMessage("火速加载中…");
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tvTitle.setText("学业规划");
        ivXz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                init();
                uploadAvatarFromAlbumRequest();
            }
        });
        dialog.show();
        dialog.setCanceledOnTouchOutside(false);
        OkGo.post(AppConstants.BASE_URL + "/rtu/tStudent.shtml")
                .tag(this)
                .cacheKey("cacheKey")
                .cacheMode(CacheMode.DEFAULT)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        removeDialog();
                        Log.e("学生列表", s);
                        Gson gson = new Gson();
                        Stulist stulist = gson.fromJson(s, Stulist.class);
                        dataBeen = stulist.getData();
                        if (dataBeen != null) {
                            if (dataBeen.size() > 0) {
                                stu = new String[dataBeen.size()];
                                for (int i = 0; i < dataBeen.size(); i++) {

                                    stu[i] = dataBeen.get(i).getName();
                                }

                            }

                            // Toast.makeText(PersonalInformationActivity.this, "请求成功" + arrayGrade[0], Toast.LENGTH_SHORT).show();
                            alertDialog = new AlertDialog.Builder(TeacherPlannActivity.this).setTitle("选择学生").setSingleChoiceItems(stu, 0, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    uid = dataBeen.get(which).getId();
                                    stuname = dataBeen.get(which).getName();
                                    etSubject.setText(stu[which]);
                                    //Toast.makeText(PersonalInformationActivity.this, "学科" + courseId, Toast.LENGTH_SHORT).show();
                                }
                            })
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                            dialog.dismiss();
                                        }

                                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    }).create();

                        }


                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        Toast.makeText(TeacherPlannActivity.this, "报告小主，服务器被外星人偷走啦~~", Toast.LENGTH_SHORT).show();
                    }
                });

        ivStu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (dataBeen != null && dataBeen.size() > 0) {
                    uid = dataBeen.get(0).getId();
                    etSubject.setText(stu[0]);
                    alertDialog.show();
                } else {
                    Toast.makeText(TeacherPlannActivity.this, "报告小主，您目前没有学生哦", Toast.LENGTH_SHORT).show();

                }
            }
        });
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(etTitle.getText())) {
                    Toast.makeText(TeacherPlannActivity.this, "报告小主，标题还没填呢~~~~", Toast.LENGTH_SHORT).show();
                    etTitle.requestFocus();
                    return;

                }
                if (TextUtils.isEmpty(etContent.getText())) {
                    Toast.makeText(TeacherPlannActivity.this, "报告小主，内容还没填呢~~~~", Toast.LENGTH_SHORT).show();
                    etContent.requestFocus();
                    return;

                }
                if (TextUtils.isEmpty(etSubject.getText())) {
                    Toast.makeText(TeacherPlannActivity.this, "报告小主，学生还没选择呢~~~~", Toast.LENGTH_SHORT).show();
                    return;

                }
                if (file == null) {
                    Toast.makeText(TeacherPlannActivity.this, "报告小主，文件还没选择呢~~~~", Toast.LENGTH_SHORT).show();
                    return;

                }
                HttpParams params = AppConstants.initPram();
                params.put("title", etTitle.getText().toString());
                params.put("content", etContent.getText().toString());
                params.put("uid", uid);
                params.put("file", file);
                Log.e("学生ID", uid + "");
                dialog.show();
                OkGo.post(AppConstants.BASE_URL + "/splan/addOrUpdate.shtml")
                        .tag(this)
                        .cacheKey("cacheKey")
                        .cacheMode(CacheMode.DEFAULT)
                        .params(params)
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(String s, Call call, Response response) {
                                removeDialog();
                                Log.e("学业规划", s);
                                Gson gson = new Gson();
                                Login login = gson.fromJson(s, Login.class);
                                if (login.getMsg().equals("timeout")) {
                                    AppConstants.gotoLogin(TeacherPlannActivity.this);
                                } else {
                                    Toast.makeText(TeacherPlannActivity.this, "报告小主，您的要求已完成。", Toast.LENGTH_SHORT).show();
                                    finish();
                                }
                            }

                            @Override
                            public void onError(Call call, Response response, Exception e) {
                                Toast.makeText(TeacherPlannActivity.this, "报告小主，服务器被外星人偷走啦~~", Toast.LENGTH_SHORT).show();
                                removeDialog();
                            }
                        });
            }
        });
    }

    /**
     * album
     */
    private void uploadAvatarFromAlbumRequest() {
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        //startActivityForResult(photoPickerIntent, REQUEST_CODE_ALBUM);
        startActivityForResult(photoPickerIntent, REQUEST_CODE_ALBUM);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != -1) {
            return;
        }
        if (requestCode == REQUEST_CODE_ALBUM && data != null) {
            Toast.makeText(TeacherPlannActivity.this, "报告小主，图片上传成功了哦~~", Toast.LENGTH_LONG).show();
            Uri newUri;
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                newUri = Uri.parse("file:///" + CropUtils.getPath(this, data.getData()));

            } else {

                newUri = data.getData();
            }
            if (newUri != null) {
                startPhotoZoom(newUri);
            } else {
                // Toast.makeText(this, "没有得到相册图片", Toast.LENGTH_LONG).show();
            }
        }
    }

    /**
     * 裁剪拍照裁剪
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        //Intent intent = new Intent("com.android.camera.action.CROP");
        Intent intent = new Intent();
        intent.setDataAndType(uri, "image/*");
        // intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        // intent.putExtra("crop", "true");// crop=true 有这句才能出来最后的裁剪页面.
        // intent.putExtra("aspectX", 1);// 这两项为裁剪框的比例.
        // intent.putExtra("aspectY", 1);// x:y=1:1
        intent.putExtra("outputX", 400);//图片输出大小
        intent.putExtra("outputY", 400);
        intent.putExtra("output", Uri.fromFile(file));
        intent.putExtra("outputFormat", "JPEG");// 返回格式
        startActivityForResult(intent, 3);
    }

    private void init() {

        file = new File(FileUtil.getCachePath(this), "user-avatar.jpg");
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            uri = Uri.fromFile(file);
        } else {
            //通过FileProvider创建一个content类型的Uri(android 7.0需要这样的方法跨应用访问)
            uri = FileProvider.getUriForFile(MyApplication.getApp(), "com.yf.useravatar", file);
        }
    }

    private void removeDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }
}
